/*
 * Copyright (C) 2017--2019, 微笑的丁总 All rights reserved
 * Author: DingJie
 * FileName: Face2ObjectUtils
 * Date: 2019/4/26 10:48 AM
 * Description: 小工具类
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号             描述
 */
package com.dimple.common.utils;

import org.apache.commons.collections.CollectionUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.*;

/**
 * 〈一句话功能简述〉<br> 小工具类
 *
 * @author dogjay
 * @create 2019/4/26
 * @since 1.0.0
 */
public class Face2ObjectUtils {
    /**
     * 获取保存文件的位置,jar所在目录的路径
     *
     * @return
     */
    public static String getUploadFilePath() {
        String path = Face2ObjectUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        path = path.substring(1, path.length());
        try {
            path = java.net.URLDecoder.decode(path, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        int lastIndex = path.lastIndexOf("/") + 1;
        path = path.substring(0, lastIndex);
        File file = new File("");
        return file.getAbsolutePath() + "/";
    }

    public static String generdateFilePath() {
        return DateUtils.parseDateToStr("yyyyMMdd/", new Date());
    }

    /**
     * 获取
     *
     * @param max
     * @param str
     * @return
     */
    public static String random(int max, String str) {
        return UUID.random(1, max) + str;
    }

    /**
     * 得到网页中图片的地址
     *
     * @param htmlStr html字符串
     * @return List<String>
     */
    public static List<String> getImgStr(String htmlStr) {
        List<String> pics = new ArrayList<String>();
        String img = "";
        Pattern p_image;
        Matcher m_image;
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = compile(regEx_img, CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;
    }

    /**
     * 返回文章中第一张图片作为封面图片
     *
     * @param imgStrList
     * @return
     */
    public static String getFirstImgSrc(List<String> imgStrList) {
        if (CollectionUtils.isNotEmpty(imgStrList)) {
            return imgStrList.get(0);
        } else {
            return "";
        }
    }


}
